import api from './api.js'
import { getQuery } from './utils.js'

// 获取内容

const query = getQuery()

let article = api.getDetail(query.id)
article.then(res => {
  if (res.errno === 0) {
    let data = res.data
    console.log(data)
    $('#title').val(data.title)
    $('#content').val(data.content)
  } else {
    console.log('res.errno:', res.errno)
  }
}).catch(err => {
  console.error(err)
})

const form = $('#editArticle')
form.submit((e) => {
  e.preventDefault()
  $('.alert.alert-success').hide()
  $('.alert.alert-warning').hide()
  $('.alert.alert-danger').hide()

  const arr = form.serializeArray()
  let data = {}
  arr.forEach(item => {
    data[item.name] = item.value
  })

  console.log(data)

  let result = api.editArticle(query.id, data)
  result.then(res => {
    if (res.errno === 0) {
      console.log(res)
      $('.alert.alert-success').show()
      setTimeout(() => {
        location.href = '/detail?id=' + query.id
      }, 1500);
    } else {
      $('.alert.alert-danger').show()
      console.log('res.errno:', res.errno)
    }
  }).catch(err => {
    console.error(err)
  })
})

